import { createApp } from "vue";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import axios from "axios";
import "./mock/index.js";

const app = createApp(App);

axios.defaults.baseURL = import.meta.env.VITE_APP_BASE_API;
axios.default.timeout = 10000;
// 添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
  (config) => {
    const token = sessionStorage.getItem("Authorization");
    if (token) {
      config.headers.Authorization = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 添加返回拦截器，判断是否401
axios.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response) {
      const { status, data } = error.response;
      switch (status) {
        case 401:
          // 服务器端返回401，说明Token已无效
          sessionStorage.removeItem("Authorization");
          router.replace({
            path: "/login",
            query: {
              redirect: router.currentRoute.fullPath,
            },
          });
          break;
      }

      if (data && data.Message) {
        message.error(data.Message);
      }
      return Promise.reject(data);
    }
  }
);
app.config.globalProperties.$axios = axios;

// 全部加载
app.use(ElementPlus);

app.use(router).use(store).mount("#app");
